package top.skihub.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.skihub.pojo.Goods;
import top.skihub.pojo.Result;
import top.skihub.service.AddGoodsService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 添加商品控制器
 */
@Slf4j
@RestController
public class AddGoodaController {
    @Autowired
    private AddGoodsService addGoodsService;

    private static final String UPLOAD_DIR = "/usr/local/javaproject/supermarket-management-system/photo";
    private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList(".jpg", ".jpeg", ".png");
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    @Value("${server.port}")
    private String port;

    @PostMapping("/addgoods")
    public Result list(@RequestParam("file") MultipartFile file,
                      @RequestParam String goodsName,
                      @RequestParam String goodsType,
                      @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                      @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
                      @RequestParam String goodsDesc,
                      @RequestParam String businessInfo,
                      @RequestParam Long price) {
        log.info("服务端口: {}, 开始添加商品接口调用，商品名称: {}, 商品类型: {}, 开始时间: {}, 结束时间: {}, 商品描述: {}, 商家信息: {}, 价格: {}", port, goodsName, goodsType, startTime, endTime, goodsDesc, businessInfo, price);
        try {
            // 基础参数验证
            if (!validateBasicParams(goodsName, goodsType, startTime, endTime, goodsDesc, businessInfo, price)) {
                return Result.error("请检查所有必填字段是否填写正确");
            }

            // 时间验证
            if (!validateTimeRange(startTime, endTime)) {
                return Result.error("商品开始时间必须早于结束时间");
            }

            // 价格验证
            if (!validatePrice(price)) {
                return Result.error("商品价格必须大于0");
            }

            // 文件验证
            if (!validateFile(file)) {
                return Result.error("请上传有效的图片文件(jpg/jpeg/png)，大小不超过5MB");
            }

            // 确保上传目录存在
            createUploadDirectoryIfNotExists();
            
            // 处理文件上传
            String imageUrl = handleFileUpload(file);
            if (imageUrl == null) {
                return Result.error("文件上传失败");
            }

            // 创建并保存商品信息
            Goods goods = createGoods(goodsName, goodsType, startTime, endTime, 
                                    goodsDesc, businessInfo, price, imageUrl);

            // 保存商品信息
            addGoodsService.addGoods(goods);
            log.info("添加商品成功:{}，服务端口: {}", goods, port);
            return Result.success();

        } catch (IOException e) {
            log.error("文件处理失败", e);
            return Result.error("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("添加商品失败", e);
            return Result.error("系统错误: " + e.getMessage());
        }
    }

    private boolean validateBasicParams(String goodsName, String goodsType, 
                                      LocalDateTime startTime, LocalDateTime endTime,
                                      String goodsDesc, String businessInfo, Long price) {
        return StringUtils.hasText(goodsName) 
            && StringUtils.hasText(goodsType)
            && startTime != null 
            && endTime != null
            && StringUtils.hasText(goodsDesc)
            && StringUtils.hasText(businessInfo)
            && price != null;
    }

    private boolean validateTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return startTime.isBefore(endTime);
    }

    private boolean validatePrice(Long price) {
        return price != null && price > 0;
    }

    private boolean validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        // 检查文件类型
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!ALLOWED_FILE_TYPES.contains(fileExtension)) {
            return false;
        }

        // 检查文件大小
        return file.getSize() <= MAX_FILE_SIZE;
    }

    private void createUploadDirectoryIfNotExists() throws IOException {
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
    }

    private String handleFileUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = System.currentTimeMillis() + fileExtension;
        
        Path filePath = Paths.get(UPLOAD_DIR, fileName);
        file.transferTo(filePath.toFile());
        
        return "/photo/" + fileName;
    }

    private Goods createGoods(String goodsName, String goodsType, 
                            LocalDateTime startTime, LocalDateTime endTime,
                            String goodsDesc, String businessInfo, 
                            Long price, String imageUrl) {
        Goods goods = new Goods();
        goods.setGoodsName(goodsName);
        goods.setGoodsType(goodsType);
        goods.setStartTime(startTime);
        goods.setEndTime(endTime);
        goods.setGoodsDesc(goodsDesc);
        goods.setBusinessInfo(businessInfo);
        goods.setPrice(price);
        goods.setGoodsImg(imageUrl);
        return goods;
    }
}
